<template>
  <div class="search">
    <van-search
      v-model="inputVal"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="$router.back()"
    />
    <my-history @search="search" v-if="list.length==0"></my-history>
    <ul class="content" v-else>
      <li
        v-for="(item, index) in list"
        :key="index"
        @click="$router.push(`/detail/${item.goods_id}`)"
      >
        <img :src="item.goods_big_logo" alt="" />
        <section>
          <h5>{{ item.goods_name }}</h5>
          <p>￥{{ item.goods_price }}</p>
        </section>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, reactive, toRefs } from "vue";
import api from "../api/index";
import myHistory from '../components/myHistory.vue';
import { useStore } from 'vuex';
export default {
  components: { myHistory },
  setup() {
    const { commit } = useStore();
    const data = reactive({
      inputVal: "",
      list: [], // 搜索的商品
    });

    const onSearch = () => {
      api.get(`/goods/search?query=${data.inputVal}`).then((res) => {
        data.list = res.message.goods;
        if (data.inputVal){
            commit('addHistory',data.inputVal);
        }
      });
    };
    const search = (val) => {
       data.inputVal = val;
       onSearch();
    }
    return {
      ...toRefs(data),
      onSearch,
      search
    };
  },
};
</script>
<style lang="scss" scoped>
.search {
  height: 100%;
}
.content {
  height: calc(100% - 54px);
  overflow: auto;
  li {
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    img {
      width: 80px;
    }
    section {
      flex: 1;
      margin-left: 10px;
      display: inline-flex;
      flex-wrap: wrap;
      align-content: space-between;
      p {
        color: red;
      }
    }
  }
}
</style>